package org.dromara.article.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.article.domain.ArticleType;
import org.dromara.article.domain.TaskLog;
import org.dromara.article.mapper.ArticleTypeMapper;
import org.dromara.article.mapper.TaskLogMapper;
import org.dromara.article.service.ArticleService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 清理上传文章定时任务
 */
@Slf4j
@Component
public class CleanArticleTask {

    @Resource
    private TaskLogMapper taskLogMapper;
    @Resource
    private ArticleService articleService;
    @Resource
    private ArticleTypeMapper articleTypeMapper;


    /**
     * 清理文章定时任务,每周执行一次
     */
    @Scheduled(cron = "0 0 8 ? * MON")
    // @Scheduled(cron = "* * * * * *")
    public void cleanArticle() {
        log.info("开始清理文章上传临时文件");
        DateTime startTime = DateUtil.date();
        TaskLog taskLog = new TaskLog();
        taskLog.setTaskName("CleanArticle");
        taskLog.setStartTime(startTime);
        StringBuilder builder = new StringBuilder(); //描述信息
        try {
            // 查询所有的文章类型
            List<ArticleType> typeList = articleTypeMapper.selectList(null);
            builder.append("清理文章类型数量为 ").append(typeList.size()).append(" 种 ");
            typeList.forEach(type -> {
                String savePath = articleService.getSavePath(type.getName());
                int size = FileUtil.loopFiles(savePath).size();
                FileUtil.del(savePath);
                builder.append(type.getName()).append(" 文章数量 ").append(size).append(" 篇 ");
            });

            taskLog.setStatus(1);
        } catch (Exception e) {

            taskLog.setStatus(0);
        }finally {
            taskLog.setTaskDesc(builder.toString());
            taskLog.setEndTime(DateUtil.date());
            taskLog.setEndTime(DateUtil.date());

            taskLogMapper.insert(taskLog);
        }
    }


}
